package com.chdwmp.product.job;

import com.chdwmp.product.bean.app.SerialActiveVo;
import com.chdwmp.product.mapper.SerialNumberMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.runtime.Desc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@EnableScheduling
@Slf4j
public class RecycleTask {

    @Autowired
    SerialNumberMapper serialNumberMapper;

    @Scheduled(cron = "0 0/5 * * * ?")
    private void dealRecycleLicense(){
        //查询保活记录表里的最新的记录和当前时间比较 是否超过5分钟。如果超过回收掉
        log.info("开始执行定时任务(回收) 查询符合条件的列表------");
        List<String> list  = serialNumberMapper.queryRecycleLicenseList();
        if(null != list && !list.isEmpty()){
            for (String s : list) {
//                log.info("开始回收序列号------");
                serialNumberMapper.updateTestServiceNumberByRecovery(s);
//                log.info("结束回收序列号------");
            }
        }
        log.info("结束执行(回收)定时任务------");
    }


    @Scheduled(cron = "0 0/2 * * * ?")
    private void dealDeviceStatus(){
        //查询保活记录表里 超过1分钟没有保活的话就设置成不在线
        log.info("开始执行定时任务(保活记录) 查询符合条件的列表------");

        //查找所有激活的imei
        List<SerialActiveVo> imeis  = serialNumberMapper.queryAllActiveImeis();
        if(null !=  imeis){
            for (SerialActiveVo serialActiveVo : imeis) {
                Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                Matcher m = p.matcher(serialActiveVo.getSerial_number());
                int count  = serialNumberMapper.queryDeviceList(serialActiveVo.getImei(),m.replaceAll(""));
                if(count > 0){
                    //设置成不在线
                    int result = serialNumberMapper.updateDeviceStatusBySeriaNumber(serialActiveVo.getImei());
                    if(result == 0){
                        log.info("执行不成功：" + "imei:" + serialActiveVo.getImei());
                    }
                }
            }
        }
        log.info("结束执行(保活记录)定时任务------");
    }
}
